import json

import requests

from bpush import BPush
from core import Message, Bot
from libs.seebug import seebug
from libs.showrto import showrto
from register import register, register_command


blank_list = [
    "723343150"
]


@register_command("妹子图")
def decorator(bot: Bot, message: Message):
    global blank_list

    if str(message.group.group_id) in blank_list:
        return

    # images = []
    #
    # for item in r.json()['data']:
    #    images.append(item['url'])
    #
    # print(images)
    # image = showrto()
    try:
        r = requests.get("https://api88.net/api/img/rand/", allow_redirects=False, verify=False)
        # r = requests.get(image)
        bot.sendImageMessage(
            message.group.group_id,
            image_list=[
                r.headers.get("Location")
                # image
            ]
        )
    except requests.exceptions.SSLError as e:
        pass


# @register_command("秀人")
# def decorator(bot: Bot, message: Message):
#     blank_list = [
#         "723343150"
#     ]
#
#     if str(message.group.group_id) in blank_list:
#         bot.sendGroupMessage(
#             message.group.group_id,
#             text="该功能未再群开放，请联系管理员开放😯!~"
#         )
#         return
#
#     # images = []
#     #
#     # for item in r.json()['data']:
#     #    images.append(item['url'])
#     #
#     # print(images)
#     image = showrto()
#     # r = requests.get("https://api88.net/api/img/rand/", allow_redirects=False)
#     # r = requests.get(image)
#     bot.sendImageMessage(
#         message.group.group_id,
#         image_list=[
#             # r.headers.get("Location")
#             image
#         ]
#     )


@register_command("查询")
def find_qq(bot: Bot, message: Message):
    pass
    # command = "".join(message.text.split("查询")).strip()
    # r = requests.get("https://cxx.yun7.me/qqapi?qq={}".format(command))
    # bot.sendGroupMessage(
    #     message.group.group_id, r.text
    # )


def recommand_get(cate_id, tag_id):
    results = []

    data = requests.post(
        "https://api.juejin.cn/recommend_api/v1/article/recommend_cate_tag_feed",
        data=json.dumps({
            "id_type": 2,
            "sort_type": 200,
            "cate_id": cate_id,
            "tag_id": tag_id,
            "cursor": "0", "limit": 5}),
        headers={
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) A"
                          "ppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36",
            "Content-Type": "application/json"
        }
    ).json()

    # print(data)

    for item in data['data']:
        article_info = item['article_info']
        article_id = article_info['article_id']
        title = article_info['title']

        results.append({"type": "Plain", "text": "{} https://juejin.cn/post/{}\n".format(title, article_id)})
    return results


@register_command("我要看文章")
def recommand_list_view(bot: Bot, message: Message):
    items = {
        '后端': {'tag_id': '6809640408797167623', 'cate_id': '6809637769959178254'},
        'java': {'tag_id': '6809640445233070094', 'cate_id': '6809637769959178254'},
        'python': {'tag_id': '6809640448827588622', 'cate_id': '6809637769959178254'},
        'go': {'tag_id': '6809640364677267469', 'cate_id': '6809637769959178254'},
        'mysql': {'tag_id': '6809640366896054286', 'cate_id': '6809637769959178254'},
        '数据库': {'tag_id': '6809640600502009863', 'cate_id': '6809637769959178254'},
        'redis': {'tag_id': '6809640371019055111', 'cate_id': '6809637769959178254'},
        'spring boot': {'tag_id': '6809641037787561992', 'cate_id': '6809637769959178254'},
        'spring': {'tag_id': '6809640703325372423', 'cate_id': '6809637769959178254'},
        '算法': {'tag_id': '6809640499062767624', 'cate_id': '6809637769959178254'},
        'kubernetes': {'tag_id': '6809640675944955918', 'cate_id': '6809637769959178254'},
        'linux': {'tag_id': '6809640385980137480', 'cate_id': '6809637769959178254'},
        'jvm': {'tag_id': '6809640696455102472', 'cate_id': '6809637769959178254'},
        '架构': {'tag_id': '6809640501776482317', 'cate_id': '6809637769959178254'},
        'spring cloud': {'tag_id': '6809641146378092552', 'cate_id': '6809637769959178254'}}

    command = "".join(message.text.split("我要看文章")).strip()
    keyword = items.get(command.lower(), None)

    if keyword:
        tag_id, cate_id = keyword.values()
        results = recommand_get(cate_id, tag_id)
        bot.sendGroupMessage(
            message.group.group_id,
            text=results
        )
        return

    bot.sendGroupMessage(
        message.group.group_id,
        text="可以查询的词: " + ",".join(items.keys())
    )


@register_command("漏洞")
def seebug_search(bot: Bot, message: Message):
    command = "".join(message.text.split("漏洞")).strip()
    if command != "":
        results = seebug(command)
        if len(results) == 0:
            return

        bot.sendGroupMessage(
            message.group.group_id,
            text=results, quote=message.message_id
        )
        return


@register_command("禁言")
def recommand_list_view(bot: Bot, message: Message):
    # command = "".join(message.text.split("禁言")).strip()

    if message.is_at:
        bot.mute(
            message.group.group_id,
            member_id=message.at_member_id,
        )
        # bot.sendGroupMessage(
        #     message.group.group_id,
        #     text="已禁言用户 {}".format(message.at_member_id)
        # )


@register_command("闭嘴")
def recommand_list_view(bot: Bot, message: Message):
    # command = "".join(message.text.split("禁言")).strip()

    if message.is_at:
        bot.mute(
            message.group.group_id,
            member_id=message.at_member_id,
        )
        # bot.sendGroupMessage(
        #     message.group.group_id,
        #     text="已禁言用户 {}".format(message.at_member_id)
        # )


@register_command("解除禁言")
def recommand_list_view(bot: Bot, message: Message):
    # command = "".join(message.text.split("禁言")).strip()

    if message.is_at:
        bot.unmute(
            message.group.group_id,
            member_id=message.at_member_id,
        )
        # bot.sendGroupMessage(
        #     message.group.group_id,
        #     text="已解除禁言用户 {}".format(message.at_member_id)
        # )


@register_command("撤回")
def recommand_list_view(bot: Bot, message: Message):
    # command = "".join(message.text.split("禁言")).strip()

    if message.is_quote:
        bot.recall(message.quote_message_id)
        # bot.recall(message.message_id)


@register_command("菜单")
def function_list(bot: Bot, message: Message):
    keys = [_ for _, regist in register.items() if regist['private'] is False]
    bot.sendGroupMessage(
        message.group.group_id,
        text="\n".join(keys)
    )


@register_command("统计推送", is_private=True)
def function_list(bot: Bot, message: Message):
    bilibili = BPush()
    bilibili_new, bilibili_already = bilibili.bilibili_show()
    bot.sendGroupMessage(
        message.group.group_id,
        text="New: {}\nAlready: {}".format(bilibili_new, bilibili_already)
    )


@register_command("穿搭更新", is_private=True)
def bclothUpdate(bot: Bot, message: Message):
    bilibili = BPush()
    bilibili.bilibili()
    bilibili_new, bilibili_already = bilibili.bilibili_show()
    bot.sendGroupMessage(
        message.group.group_id,
        text="Updated!\nNew: {}\nAlready: {}".format(bilibili_new, bilibili_already)
    )


@register_command("我要学穿搭")
def iwanto_study_cloth(bot: Bot, message: Message):
    bilibili = BPush()
    item = bilibili.get_one()
    if not item:
        return

    title = item['title']
    pic = item['pic']
    bvid = item['bvid']

    bot.sendGroupMessage(
        target=message.group.group_id,
        text=[
            {
                "type": "Xml",
                "xml": """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <msg serviceID="1" brief="定时推送"
    action="web" url="https://www.bilibili.com/video/{}">
    <item>
    <title>{}</title>
    <picture cover="{}"/>
    </item>
    </msg>""".format(bvid, title, pic)
            }
        ]
    )


# @register_command("秀人")
# def decorator(bot: Bot, message: Message):
#     blank_list = [
#         "723343150"
#     ]
#
#     if str(message.group.group_id) in blank_list:
#         bot.sendGroupMessage(
#             message.group.group_id,
#             text="该功能未再群开放，请联系管理员开放😯!~"
#         )
#         return
#
#     # images = []
#     #
#     # for item in r.json()['data']:
#     #    images.append(item['url'])
#     #
#     # print(images)
#     image = showrto()
#     # r = requests.get("https://api88.net/api/img/rand/", allow_redirects=False)
#     # r = requests.get(image)
#     bot.sendImageMessage(
#         message.group.group_id,
#         image_list=[
#             # r.headers.get("Location")
#             image
#         ]
#     )



if __name__ == '__main__':
    pass
    # for key, value in register.items():
    #     print(key, value)

    # r = requests.get("https://api88.net/api/img/rand/", allow_redirects=False)
    # print(r.headers.get("Location"))

    # r = requests.get("http://gank.io/images/f12526b3e9654a47842db6ce21222874")
    # print(r.text)
    # bot = Bot(auth_key="12345678", qq=1398231927)
    # bot.sendGroupMessage(
    #     target=618155895,
    #     text="https://www.bilibili.com/video/BV1q64y1Q7eN"
    # )
